package com.clei.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 钉钉智能机器人 util
 *
 * @author Y
 * @date 2023-02-24
 */
public class DingTalkRobotUtil {

    /**
     * 网络钩子url
     */
    private static final String WEBHOOK = "https://oapi.dingtalk.com";

    /**
     * accessToken
     */
    private static final String ACCESS_TOKEN = "";

    /**
     * accessSecret
     */
    private static final String ACCESS_SECRET = "";

    /**
     * 签名算法
     */
    private static final String SIGN_ALGORITHM = "HmacSHA256";

    /**
     * 默认字符集
     */
    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 发送文本消息
     *
     * @param message 消息
     */
    public static void sendTxtMessage(String message) {
        if (StringUtil.isBlank(message)) {
            return;
        }
        // 消息内容
        Map<String, Object> json = new HashMap<>(2);
        Map<String, String> content = new HashMap<>(1);
        content.put("content", message);
        json.put("msgtype", "text");
        json.put("text", content);
        // 签名
        long timestamp = System.currentTimeMillis();
        String sign = sign(timestamp);
        // 发起http请求
        String url = null;
        String res = null;
        try {
            url = String.format("%s/robot/send?access_token=%s&timestamp=%s&sign=%s", WEBHOOK, ACCESS_TOKEN, timestamp, sign);
            res = OkHttpUtil.doPostJson(url, json, null);
            PrintUtil.log("发送钉钉消息成功 param : {}, url : {}, res : {}", json, url, res);
        } catch (Exception e) {
            PrintUtil.log("发送钉钉消息出错 param : {}, url : {}, res : {}", json, url, res, e);
        }
    }

    /**
     * 签名
     *
     * @param timestamp 时间戳
     * @return 签名
     */
    private static String sign(long timestamp) {
        try {
            String stringToSign = timestamp + "\n" + ACCESS_SECRET;
            Mac mac = Mac.getInstance(SIGN_ALGORITHM);
            mac.init(new SecretKeySpec(ACCESS_SECRET.getBytes(StandardCharsets.UTF_8), SIGN_ALGORITHM));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            return URLEncoder.encode(Base64Util.encode(signData), DEFAULT_CHARSET);
        } catch (Exception e) {
            PrintUtil.log("create sign error. timestamp : {}, accessSecret : {}", timestamp, ACCESS_SECRET, e);
        }
        return null;
    }
}
